﻿#coding: utf-8

require 'sinatra/jsonp'

get '/node/:id' do
	content_type :json
	n = Node.get(params[:id])
	if n.nil? then
		404
	else
		res = n.to_json_with_contents
		if params[:format] == 'js' then
			JSONP res
		else
			body(n.to_json_with_contents)
			200
		end
	end
end

get '/node/t/:title' do
	node = Node.first(:title => params[:title])
	if node.nil? then
		404
	else
		res = node.to_json_with_contents
		if params[:format] == 'js' then
			JSONP res
		else
			body(node.to_json_with_contents)
			200
		end
	end
end

get '/nodes/all' do
	nodes = []
	Node.all.each {|n| nodes << n unless n.nil?}
	if nodes.empty? then
		404
	else
		res = nodes.to_json
		if params[:format] == 'js' then
			JSONP res
		else
			body(res)
			200
		end
	end
end

put '/node' do
	puts request.body.string
	begin
		data = JSON.parse(request.body.string)
	rescue JSON::ParserError
		400
	end
	if data.nil? or not data.has_key?('title') or not data.has_key?('thematic_id')
		400
	else
		n = Node.create(
			:title => data['title'],
			:thematic_id => data['thematic_id']
		)
		if n.save then
			body(n.id.to_s)
			200
		else
			400
		end
	end
end

get '/node/linked/:id' do
	node = Node.get(params[:id])
	if node.nil? then
		404
	else
		res = node.findLinkedNodes.to_json
		if params[:format] == 'js' then
			JSONP res
		else
			body(res)
			200
		end
	end
end

post '/node/:id' do
	node = Node.get(params[:id])
	if node.nil? then
		404
	else
		if node.title != data['title'] then
			node.update(:title => data['title'])
		end
		200
	end
end

delete '/node/:id' do
	node = Node.get(params[:id])
	if node.nil? then
		404
	elsif user.destroy then	
		200
	else
		400
	end
end
